package ChatRoom;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class multiClient extends JFrame implements ActionListener, Runnable {
    private final JTextField tfServerIP = new JTextField();
    private final JTextField tfServerPort = new JTextField();
    private final JTextArea taTalkMessage = new JTextArea();
    private final JTextField tfSendMessage = new JTextField();
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    public static void main(String[] args) {
        TCPClientFrame tsf = new TCPClientFrame();
        //在消息框提示用户连接到服务器
        tsf.changeTalkMessage("请连接服务器...");
        tsf.initFrame();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        switch (actionCommand) {
            case "send" -> {
                String message = tfSendMessage.getText();
                if (message.length() == 0) {
                    JOptionPane.showMessageDialog(this, "发送的信息不能为空!");
                } else {
                    sendMessage(message, true);
                }
            }
            case "conn" -> connectToServer();
            case "exit" -> closeConnection();
        }
    }

    private void connectToServer() {
        String serverIP = tfServerIP.getText();
        int port = Integer.parseInt(tfServerPort.getText());

        try {
            socket = new Socket(serverIP, port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            changeTalkMessage("成功连接到服务器！");
            new Thread(this).start();  // 启动接收消息的线程
        } catch (IOException e) {
            e.printStackTrace();
            changeTalkMessage("连接服务器失败！");
        }
    }

    private void closeConnection() {
        boolean isClientClose = true;
        sendMessage("bye", false);
        changeTalkMessage("正在关闭连接...");
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            String message;
            while ((message = in.readLine()) != null) {
                if ("bye".equalsIgnoreCase(message)) {
                    changeTalkMessage("服务器已关闭连接！");
                    break;
                }
                changeTalkMessage(message);  // 显示从服务器接收到的消息
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendMessage(String message, boolean isPrintMessage) {
        if (socket == null || socket.isClosed() || !socket.isConnected()) {
            changeTalkMessage("客户端与服务器未连接！");
            return;
        }
        out.println(message);  // 发送消息给服务器
        if (isPrintMessage) {
            changeTalkMessage("我: " + message);
        }
    }

    private void changeTalkMessage(String message) {
        SwingUtilities.invokeLater(() -> {
            taTalkMessage.append(message + "\n");
            taTalkMessage.setCaretPosition(taTalkMessage.getDocument().getLength());
        });
    }

}